<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>信任博弈 - 历史记录</title>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="animations/animations.css">
    <style>
        .container { max-width: 900px; }
        .toolbar { display: flex; gap: 10px; justify-content: center; margin-bottom: 10px; }
        .summary { text-align: center; margin-bottom: 20px; }
        
        /* 页面头部 */
        .page-header {
            margin-bottom: 15px;
        }
        
        .page-header h1 {
            margin: 10px 0;
            text-align: center;
        }
        
        .breadcrumb { 
            display: flex; 
            gap: 10px; 
            margin-bottom: 10px; 
            align-items: center; 
        }
        .breadcrumb a { color: #3498db; text-decoration: none; }
        .breadcrumb .separator { color: #999; }
        
        /* 主要统计 */
        .main-stats {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
            margin-bottom: 15px;
        }
        
        /* 详细统计折叠面板 */
        .stats-details {
            margin-bottom: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            overflow: hidden;
        }
        
        .stats-details summary {
            padding: 10px 15px;
            font-weight: 500;
            cursor: pointer;
            background: #f0f2f5;
            color: #3498db;
        }
        
        .stats-details summary:hover {
            background: #e9ecef;
        }
        
        .stats-details[open] summary {
            border-bottom: 1px solid #e0e0e0;
        }
        
        .stats-details .stats-cards {
            padding: 10px;
        }
        
        /* 策略徽章样式 */
        .badge {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
            color: white;
            margin-right: 5px;
        }
        .badge-good { background-color: #27ae60; }
        .badge-bad { background-color: #c0392b; }
        .badge-fair { background-color: #f39c12; }
        .badge-psychological { background-color: #8e44ad; }
        .badge-vengeful { background-color: #d35400; }
        
        /* 收益颜色 */
        .gain-positive { color: #27ae60; }
        .gain-negative { color: #c0392b; }
        .gain-zero { color: #7f8c8d; }
        
        /* 欺骗回合标记 */
        .deception-row { background-color: #ffecec; }
        .deception-row td { position: relative; }
        .deception-row td:first-child::before {
            content: "!";
            position: absolute;
            left: -5px;
            color: #c0392b;
            font-weight: bold;
        }
        
        /* 统计卡片 */
        .stats-cards {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 10px;
            margin-bottom: 15px;
        }
        .stat-card {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 10px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            text-align: center;
        }
        .stat-card .stat-title {
            font-size: 13px;
            color: #7f8c8d;
            margin-bottom: 5px;
        }
        .stat-card .stat-value {
            font-size: 18px;
            font-weight: bold;
            color: #2c3e50;
        }
        
        /* 筛选区 */
        .filters {
            background: #f8f9fa;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 15px;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: center;
        }
        .filter-group {
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .filter-group label {
            font-size: 14px;
            color: #555;
        }
        .filter-group select {
            padding: 5px 10px;
            border-radius: 4px;
            border: 1px solid #ddd;
        }
        
        /* 历史表格容器 */
        .history-container {
            overflow-x: auto;
            margin-bottom: 15px;
            border-radius: 8px;
            background: #fff;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        
        /* 历史表格样式 */
        #historyTable {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }
        
        #historyTable th {
            background: #f8f9fa;
            padding: 8px;
            text-align: center;
            font-weight: 600;
            color: #555;
            position: sticky;
            top: 0;
            z-index: 10;
            box-shadow: 0 1px 0 rgba(0,0,0,0.1);
        }
        
        #historyTable td {
            padding: 8px;
            text-align: center;
            border-bottom: 1px solid #eee;
        }
        
        /* 响应式调整 */
        @media (max-width: 768px) {
            .page-header h1 {
                font-size: 24px;
                margin: 8px 0;
            }
            
            .main-stats {
                grid-template-columns: repeat(3, 1fr);
                gap: 8px;
            }
            
            .stats-cards {
                grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
                gap: 8px;
            }
            
            .stat-card {
                padding: 8px;
            }
            
            .stat-card .stat-title {
                font-size: 12px;
            }
            
            .stat-card .stat-value {
                font-size: 16px;
            }
            
            .filters {
                padding: 10px;
                gap: 8px;
            }
            
            .filter-group {
                flex: 1 0 45%;
            }
            
            .filter-group select {
                flex: 1;
            }
            
            #historyTable th,
            #historyTable td {
                padding: 6px 4px;
                font-size: 12px;
            }
            
            .badge {
                padding: 1px 6px;
                font-size: 10px;
            }
            
            .stats-details summary {
                padding: 8px 12px;
                font-size: 14px;
            }
        }
        
        @media (max-width: 480px) {
            .page-header h1 {
                font-size: 20px;
            }
            
            .main-stats {
                grid-template-columns: 1fr;
                gap: 6px;
            }
            
            .stats-cards {
                grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
                gap: 6px;
            }
            
            /* 隐藏部分列 */
            #historyTable th:nth-child(3),
            #historyTable td:nth-child(3) {
                display: none; /* 隐藏增值列 */
            }
            
            /* 在极小屏幕上可以考虑隐藏更多列 */
            @media (max-width: 360px) {
                #historyTable th:nth-child(2),
                #historyTable td:nth-child(2) {
                    display: none; /* 隐藏投资列 */
                }
            }
            
            .filter-group {
                flex: 1 0 100%;
            }
            
            .filters button {
                flex: 1;
                padding: 6px;
                font-size: 12px;
            }
            
            .toolbar {
                flex-direction: column;
                gap: 6px;
            }
            
            .toolbar button {
                width: 100%;
            }
        }
    </style>
    <script type="module">
        // 导入资源提取函数
        import { extractResourceValue } from './js/modules/resources.js';
        
        document.addEventListener('DOMContentLoaded', function() {
            // 显示页面（animations.css 初始将 body 设为透明）
            document.body.classList.add('loaded');
            const historyTableBody = document.getElementById('historyTableBody');
            const summaryPlayer = document.getElementById('summaryPlayer');
            const summaryAI = document.getElementById('summaryAI');
            const summaryWealth = document.getElementById('summaryWealth');

            // 1) 优先读取URL中的会话数据（来自游戏页）
            let fromHash = [];
            const match = location.hash.match(/session=([^&]+)/);
            if (match && match[1]) {
                try {
                    fromHash = JSON.parse(decodeURIComponent(atob(match[1])));
                } catch (e) {
                    fromHash = [];
                }
            }

            // 2) 再读取本地存储累积历史
            let fromStorage = [];
            try {
                fromStorage = JSON.parse(localStorage.getItem('trust_fall_history') || '[]');
            } catch (e) {
                fromStorage = [];
            }

            // 合并两部分数据（去重简单处理：按对象序列化字符串集）
            const map = new Set();
            const data = [];
            const allRecords = [...fromStorage, ...fromHash];
            allRecords.forEach(rec => {
                const key = JSON.stringify(rec);
                if (!map.has(key)) {
                    map.add(key);
                    data.push(rec);
                }
            });

            // 计算统计数据
            let totalInvestment = 0;
            let totalReturn = 0;
            let totalMultiplied = 0;
            let deceptionCount = 0;
            let maxInvestment = 0;
            let maxReturn = 0;
            let maxPlayerGain = -Infinity;
            let maxAiGain = -Infinity;
            let bestRound = null;
            let worstRound = null;

            // 策略计数
            const strategyCounts = {
                good: 0,
                bad: 0,
                fair: 0,
                psychological: 0,
                vengeful: 0
            };

            // 获取策略名称和徽章类
            function getStrategyInfo(strategy) {
                const names = {
                    'good': '好人AI',
                    'bad': '坏人AI',
                    'fair': '公平AI',
                    'psychological': '心理战AI',
                    'vengeful': '报复性AI'
                };
                
                return {
                    name: names[strategy] || strategy,
                    class: `badge-${strategy}`
                };
            }

            // 判断是否欺骗回合（心理战AI + 返还率低）
            function isDeceptionRound(record) {
                return record.strategy === 'psychological' && 
                       parseFloat(record.returnRate) <= 0.15;
            }

            // 获取收益样式类
            function getGainClass(value) {
                if (value > 0) return 'gain-positive';
                if (value < 0) return 'gain-negative';
                return 'gain-zero';
            }

            historyTableBody.innerHTML = '';
            let player = 0, ai = 0;
            if (data.length === 0) {
                const tr = document.createElement('tr');
                tr.innerHTML = `<td colspan="7" style="color:#777;">暂无历史记录</td>`;
                historyTableBody.appendChild(tr);
            } else {
                data.forEach(record => {
                    // 更新统计数据 - 使用通用提取函数
                    totalInvestment += extractResourceValue(record.investment);
                    totalReturn += extractResourceValue(record.returnAmount);
                    totalMultiplied += extractResourceValue(record.multipliedAmount);
                    
                    if (isDeceptionRound(record)) {
                        deceptionCount++;
                    }
                    
                    // 使用通用提取函数获取各项资源值
                    let investmentValue = extractResourceValue(record.investment);
                    let returnValue = extractResourceValue(record.returnAmount);
                    let playerGainValue = extractResourceValue(record.playerGain);
                    let aiGainValue = extractResourceValue(record.aiGain);
                    
                    // 更新最大值统计
                    if (investmentValue > maxInvestment) {
                        maxInvestment = investmentValue;
                    }
                    
                    if (returnValue > maxReturn) {
                        maxReturn = returnValue;
                    }
                    
                    if (playerGainValue > maxPlayerGain) {
                        maxPlayerGain = playerGainValue;
                        bestRound = record;
                    }
                    
                    if (playerGainValue < maxPlayerGain && worstRound === null) {
                        worstRound = record;
                    }
                    
                    if (aiGainValue > maxAiGain) {
                        maxAiGain = aiGainValue;
                    }
                    
                    // 更新策略计数
                    if (record.strategy && strategyCounts[record.strategy] !== undefined) {
                        strategyCounts[record.strategy]++;
                    }

                    const tr = document.createElement('tr');
                    
                    // 如果是欺骗回合，添加样式
                    if (isDeceptionRound(record)) {
                        tr.classList.add('deception-row');
                        tr.title = '这一轮AI可能使用了欺骗策略';
                    }
                    
                    // 获取策略信息
                    const strategyInfo = getStrategyInfo(record.strategy);
                    
                    // 格式化策略显示
                    let strategyDisplay = `<span class="badge ${strategyInfo.class}">${strategyInfo.name}</span>`;
                    
                    // 如果有返还率信息，添加到显示
                    if ((record.strategy === 'psychological' || record.strategy === 'vengeful') && record.returnRate) {
                        strategyDisplay += ` <small>(${Math.round(parseFloat(record.returnRate) * 100)}%)</small>`;
                    }
                    
                    // 使用通用提取函数获取增值金额
                    let multipliedValue = extractResourceValue(record.multipliedAmount);
                    
                    tr.innerHTML = `
                        <td>${record.round ?? '-'}</td>
                        <td>${investmentValue}</td>
                        <td>${multipliedValue}</td>
                        <td>${returnValue}</td>
                        <td class="${getGainClass(playerGainValue)}">${playerGainValue > 0 ? '+' : ''}${playerGainValue}</td>
                        <td class="${getGainClass(aiGainValue)}">${aiGainValue > 0 ? '+' : ''}${aiGainValue}</td>
                        <td>${strategyDisplay}</td>
                    `;
                    historyTableBody.appendChild(tr);
                    player += playerGainValue;
                    ai += aiGainValue;
                });
                
                // 填充统计卡片
                const avgInvestment = data.length > 0 ? (totalInvestment / data.length).toFixed(1) : 0;
                const avgReturn = data.length > 0 ? (totalReturn / data.length).toFixed(1) : 0;
                const avgReturnRate = totalMultiplied > 0 ? ((totalReturn / totalMultiplied) * 100).toFixed(1) : 0;
                
                document.getElementById('statAvgInvestment').textContent = avgInvestment;
                document.getElementById('statAvgReturn').textContent = avgReturn;
                document.getElementById('statAvgReturnRate').textContent = avgReturnRate + '%';
                document.getElementById('statDeceptionCount').textContent = deceptionCount;
                document.getElementById('statMaxInvestment').textContent = maxInvestment;
                document.getElementById('statMaxReturn').textContent = maxReturn;
                
                // 填充策略统计
                document.getElementById('statGoodCount').textContent = strategyCounts.good;
                document.getElementById('statBadCount').textContent = strategyCounts.bad;
                document.getElementById('statFairCount').textContent = strategyCounts.fair;
                document.getElementById('statPsychologicalCount').textContent = strategyCounts.psychological;
                document.getElementById('statVengefulCount').textContent = strategyCounts.vengeful;
                
                // 设置筛选器选项
                const strategyFilter = document.getElementById('filterStrategy');
                if (strategyFilter) {
                    const strategies = Object.keys(strategyCounts).filter(s => strategyCounts[s] > 0);
                    strategies.forEach(s => {
                        const option = document.createElement('option');
                        option.value = s;
                        option.textContent = getStrategyInfo(s).name;
                        strategyFilter.appendChild(option);
                    });
                }
                
                // 初始化筛选和排序事件
                initFiltersAndSorting(data);
            }

            summaryPlayer.textContent = player;
            summaryAI.textContent = ai;
            summaryWealth.textContent = player + ai;

            // 筛选和排序功能
            function initFiltersAndSorting(originalData) {
                const filterStrategy = document.getElementById('filterStrategy');
                const sortBy = document.getElementById('sortBy');
                const filterBtn = document.getElementById('applyFilters');
                const resetBtn = document.getElementById('resetFilters');
                
                if (!filterBtn || !resetBtn) return;
                
                filterBtn.addEventListener('click', applyFilters);
                resetBtn.addEventListener('click', resetFilters);
                
                function applyFilters() {
                    let filtered = [...originalData];
                    
                    // 策略筛选
                    if (filterStrategy.value !== 'all') {
                        filtered = filtered.filter(record => record.strategy === filterStrategy.value);
                    }
                    
                    // 排序
                    if (sortBy.value !== 'round') {
                        filtered.sort((a, b) => {
                            // 使用通用提取函数获取各项资源值
                            let aPlayerGain = extractResourceValue(a.playerGain);
                            let bPlayerGain = extractResourceValue(b.playerGain);
                            let aAiGain = extractResourceValue(a.aiGain);
                            let bAiGain = extractResourceValue(b.aiGain);
                            let aInvestment = extractResourceValue(a.investment);
                            let bInvestment = extractResourceValue(b.investment);
                            
                            switch (sortBy.value) {
                                case 'playerGain':
                                    return bPlayerGain - aPlayerGain;
                                case 'aiGain':
                                    return bAiGain - aAiGain;
                                case 'investment':
                                    return bInvestment - aInvestment;
                                case 'returnRate':
                                    return (parseFloat(b.returnRate || 0) - parseFloat(a.returnRate || 0));
                                default:
                                    return 0;
                            }
                        });
                    }
                    
                    renderFilteredData(filtered);
                }
                
                function resetFilters() {
                    filterStrategy.value = 'all';
                    sortBy.value = 'round';
                    renderFilteredData(originalData);
                }
                
                function renderFilteredData(filtered) {
                    historyTableBody.innerHTML = '';
                    
                    if (filtered.length === 0) {
                        const tr = document.createElement('tr');
                        tr.innerHTML = `<td colspan="7" style="color:#777;">没有符合条件的记录</td>`;
                        historyTableBody.appendChild(tr);
                        return;
                    }
                    
                    filtered.forEach(record => {
                        const tr = document.createElement('tr');
                        
                        if (isDeceptionRound(record)) {
                            tr.classList.add('deception-row');
                            tr.title = '这一轮AI可能使用了欺骗策略';
                        }
                        
                        const strategyInfo = getStrategyInfo(record.strategy);
                        let strategyDisplay = `<span class="badge ${strategyInfo.class}">${strategyInfo.name}</span>`;
                        
                        if ((record.strategy === 'psychological' || record.strategy === 'vengeful') && record.returnRate) {
                            strategyDisplay += ` <small>(${Math.round(parseFloat(record.returnRate) * 100)}%)</small>`;
                        }
                        
                        // 使用通用提取函数获取各项资源值
                        let investmentValue = extractResourceValue(record.investment);
                        let multipliedValue = extractResourceValue(record.multipliedAmount);
                        let returnValue = extractResourceValue(record.returnAmount);
                        let playerGainValue = extractResourceValue(record.playerGain);
                        let aiGainValue = extractResourceValue(record.aiGain);
                        
                        tr.innerHTML = `
                            <td>${record.round ?? '-'}</td>
                            <td>${investmentValue}</td>
                            <td>${multipliedValue}</td>
                            <td>${returnValue}</td>
                            <td class="${getGainClass(playerGainValue)}">${playerGainValue > 0 ? '+' : ''}${playerGainValue}</td>
                            <td class="${getGainClass(aiGainValue)}">${aiGainValue > 0 ? '+' : ''}${aiGainValue}</td>
                            <td>${strategyDisplay}</td>
                        `;
                        historyTableBody.appendChild(tr);
                    });
                }
            }

            // 移除旧的backBtn事件绑定，已通过nav-link替代

            document.getElementById('clearBtn').addEventListener('click', () => {
                localStorage.removeItem('trust_fall_history');
                location.reload();
            });
        });
    </script>
</head>
<body>
<div class="container">
    <div class="page-header">
        <div class="breadcrumb">
            <a href="index.html">首页</a>
            <span class="separator">›</span>
            <span>历史记录</span>
        </div>
        
        <h1>历史记录</h1>
        
        <div class="nav-links">
            <a href="index.html" class="nav-link">
                <span>🎮 返回游戏</span>
            </a>
            <a href="rooms.html" class="nav-link">
                <span>🏠 房间系统</span>
            </a>
            <a href="friends.html" class="nav-link">
                <span>👥 好友对战</span>
            </a>
        </div>
    </div>
    
    <!-- 主要统计卡片 -->
    <div class="main-stats">
        <div class="stat-card">
            <div class="stat-title">你的累计收益</div>
            <div class="stat-value" id="summaryPlayer">0</div>
        </div>
        <div class="stat-card">
            <div class="stat-title">AI累计收益</div>
            <div class="stat-value" id="summaryAI">0</div>
        </div>
        <div class="stat-card">
            <div class="stat-title">总创造财富</div>
            <div class="stat-value" id="summaryWealth">0</div>
        </div>
    </div>
    
    <!-- 可折叠的详细统计 -->
    <details class="stats-details">
        <summary>查看详细统计</summary>
        <div class="stats-cards">
            <div class="stat-card">
                <div class="stat-title">平均投资</div>
                <div class="stat-value" id="statAvgInvestment">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-title">平均返还</div>
                <div class="stat-value" id="statAvgReturn">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-title">平均返还率</div>
                <div class="stat-value" id="statAvgReturnRate">0%</div>
            </div>
            <div class="stat-card">
                <div class="stat-title">欺骗回合数</div>
                <div class="stat-value" id="statDeceptionCount">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-title">好人AI次数</div>
                <div class="stat-value" id="statGoodCount">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-title">坏人AI次数</div>
                <div class="stat-value" id="statBadCount">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-title">公平AI次数</div>
                <div class="stat-value" id="statFairCount">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-title">心理战AI次数</div>
                <div class="stat-value" id="statPsychologicalCount">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-title">报复性AI次数</div>
                <div class="stat-value" id="statVengefulCount">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-title">最高投资</div>
                <div class="stat-value" id="statMaxInvestment">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-title">最高返还</div>
                <div class="stat-value" id="statMaxReturn">0</div>
            </div>
        </div>
    </details>
    
    <div class="filters">
        <div class="filter-group">
            <label for="filterStrategy">策略:</label>
            <select id="filterStrategy">
                <option value="all">全部</option>
            </select>
        </div>
        <div class="filter-group">
            <label for="sortBy">排序:</label>
            <select id="sortBy">
                <option value="round">回合</option>
                <option value="playerGain">你的收益</option>
                <option value="aiGain">AI收益</option>
                <option value="investment">投资额</option>
                <option value="returnRate">返还率</option>
            </select>
        </div>
        <button id="applyFilters">应用</button>
        <button id="resetFilters">重置</button>
    </div>
    
    <div class="history-container">
        <table id="historyTable">
            <thead>
            <tr>
                <th>回合</th>
                <th>投资</th>
                <th>增值</th>
                <th>返还</th>
                <th>你的收益</th>
                <th>AI收益</th>
                <th>AI策略</th>
            </tr>
            </thead>
            <tbody id="historyTableBody"></tbody>
        </table>
    </div>
    
    <div class="toolbar">
        <button id="clearBtn">清空历史</button>
    </div>
</div>
</body>
</html>